package com.mnemonic.views;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.mnemonic.game.Game;
import com.mnemonic.lifecycle.Lifecycles;
import com.mnemonic.storage.impl.GameStorageService;
import com.mnemonic.support.swing.Dialogs;

/**
 * 归档数据页面
 * 
 * @author lifeng
 * @date 2021/05/12
 */
public class ArchivePanel extends AbstractPanel {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private DefaultTableModel model = null;
    private GameStorageService gameStorageService;
    private List<Game> games;

    public ArchivePanel() {
        this.setLayout(new BorderLayout(0, 0));
        JScrollPane jsp = new JScrollPane();
        this.add(jsp, BorderLayout.CENTER);
        JPanel opsPanel = new JPanel();
        opsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        JButton load = new JButton("加载");
        load.addActionListener((e) -> {
            this.open();
        });
        opsPanel.add(load);
        JButton del = new JButton("清空");
        del.addActionListener((e) -> {
            this.gameStorageService.clear();
            this.games.clear();
            this.model.setRowCount(0);
        });
        opsPanel.add(del);
        JButton refresh = new JButton("刷新");
        refresh.addActionListener((e) -> {
            this.load();
        });
        opsPanel.add(refresh);
        this.add(opsPanel, BorderLayout.SOUTH);
        String[] columnName = {"ID", "名称", "第几回合", "玩家数", "难度"};
        this.model = new DefaultTableModel(columnName, 0);
        table = new JTable(this.model);
        jsp.setViewportView(table);
        jsp.validate();
        jsp.repaint();
    }

    @Override
    public void init() {
        if (!(this.state == null || this.state == Lifecycles.Start)) {
            return;
        }
        super.init();
        this.gameStorageService = new GameStorageService();
        this.load();
    }

    private void load() {
        this.games = this.gameStorageService.list();
        this.model.setRowCount(0);
        for (Game game : this.games) {
            Object[] rowData = new Object[7];
            rowData[0] = game.getId();
            rowData[1] = game.getName();
            rowData[2] = game.getBouts().size();
            rowData[3] = game.getPlayers().size();
            rowData[4] = game.getLevel().toString();
            this.model.addRow(rowData);
        }
    }

    /**
     * 记载存档继续游戏
     */
    private void open() {
        int index = table.getSelectedRow();
        if (index < 0) {
            Dialogs.error("操作提醒", "请选择一个存档！");
            return;
        }

        // 需要加载的存档
        Game game = this.games.get(index);

        // 开启对战
        new GamePage(game).setVisible(true);
    }
}